<include file="Public/header1" title="直播详情"/>



<div class="main">
    <div class="wrap">
        <div class="content">
            <div class="nav">
                <ul class="nav-pills">
                    <li><a href="{:U('Reporter/index')}">首页</a></li>
                    <?php if(isset($_GET['sid'])) { ?>
                    <li><a href="{:u('Special/index')}">专题管理</a></li>
                    <li><a href="{:u('Special/details')}?id={$Think.get.sid}">直播管理</a></li>
                    <?php } else { ?>
                    <li><a href="{:u('Live/index')}">直播管理</a></li>
                    <?php } ?>
                    <li><a href="">{$streamList[0]['title']}</a></li>
                </ul>
                <ul class="nav-tabs">
                    <li data-href="live" class="tab active">直播</li>
                    <li data-href="settings" class="tab">设置详情</li>
                    <li data-href="channel" class="tab">机位管理</li>
                    <li data-href="comment" class="tab">评论管理</li>
                    <li class="clr"></li>
                </ul>
            </div>
            <ul class="tabs">
                <li class="tab-content active" id="live">
                    <div class="link"><img src="__PUBLIC__/img/link.png" alt="">视频地址</div>
                    <ul id="addr-model">
                    <li class="add-list">
                            <p>自适应：</p>
                            <input type="text" id="jw-addr"
                                   value="http://plive.appwuhan.com/{:date('Ymd',$streamList[0]['create_time'])}/jw_{:md5($streamList[0]['group_id'])}.html"
                                   readonly>
                            <span class="label" data-label="OK" data-clipboard-target="#jw-addr">复制</span>
                        </li>
                        <li class="add-list">
                            <p>PC端：</p>
                            <input type="text" id="pc-addr"
                                   value="http://plive.appwuhan.com/{:date('Ymd',$streamList[0]['create_time'])}/whtv_{:md5($streamList[0]['group_id'])}.html"
                                   readonly>
                            <span class="label" data-label="OK" data-clipboard-target="#pc-addr">复制</span>
                        </li>
                        <li class="add-list">
                            <p>移动端：</p>
                            <input type="text" id="yun-addr"
                                   value="http://plive.appwuhan.com/{:date('Ymd',$streamList[0]['create_time'])}/whtvm_{:md5($streamList[0]['group_id'])}.html"
                                   readonly>
                            <span class="label" data-label="OK" data-clipboard-target="#yun-addr">复制</span>
                        </li>
                    </ul>
                    <ul class="live-panel statusbtnlist" data-groupid="{$streamList[0]['group_id']}">
                        <li class="pull-left panel-btn <?php if($streamList[0]['group_status'] == 0) { ?>active<?php } ?>" id="setPreview" data-status="0" >预告</li>
                        <!--<li class="pull-left panel-btn">测试</li>-->
                        <li class="pull-left panel-btn <?php if($streamList[0]['group_status'] == 1 || $streamList[0]['group_status'] == 2) { ?>active<?php } ?>" id="setLive" data-status="1">直播</li>
                        <li class="pull-left panel-btn <?php if($streamList[0]['group_status'] == 3) { ?>active<?php } ?>" id="setrReview" data-status="3">回看</li>
                    </ul>
                    <ul class="live-items">
                        <volist name="streamList" id="vo">
                        <li class="item">
                            <div class="img">
                                <div id="J_prismPlayer_{$vo.id}" class="prism-player"></div>
                                <script>
                                    // 初始化播放器
                                    var player_{$vo.id} = new prismplayer({
                                        id: "J_prismPlayer_{$vo.id}", // 容器id
                                    <?php if($vo['userchannel']==55  || $vo['is_device']==1){ ?>
                                        source: '{:authAliyun("rtmp://jwlive.appwuhan.com/jw/".$vo['realnamepy'])}',// 视频地址
                                                <?php } else if($vo['userchannel']==57){ ?>
                                        source: '{:authAliyun("rtmp://jwlive.appwuhan.com/jwdev/".$vo['group_id']."_".$vo['user_id'])}',
                                                <?php }else{ ?>
                                        source: '{:authAliyun("rtmp://jwlive.appwuhan.com/jw/".$vo['group_id']."_".$vo['user_id'])}',// 视频地址
                                                <?php }　?>
                                    autoplay: true,
                                            isLive:true,
                                            cover:"{$vo.image_url}",
                                            width: "278px",
                                            height: "197px",
                                            extraInfo:{
                                        "fullTitle":"{$vo.title}-{$vo.realname}",
                                                "liveRetry":1
                                    }
                                    });


                                    player_{$vo.id}.on("liveStreamStop", function() {
                                        $(player_{$vo.id}).parents('.detail-list').find('.text-info').load("{:U('showBTNs')}?id="+item.data('id'));
                                    });
                                    player_{$vo.id}.on("play", function() {
                                        $(player_{$vo.id}).parents('.detail-list').find('.text-info').load("{:U('showBTNs')}?id="+item.data('id'));
                                    });
                                </script>

                            </div>
                            <div class="info">
                                <div class="live-name">
                                    <?php if($vo['pos_name']){echo $vo['pos_name'];}else{echo $i.'号机位';} ?>
                                    <?php if($vo['z_status'] == 0) { ?>
                                    <span class="icon pre">预告</span></div>
                                    <?php } elseif($vo['z_status'] == 1) { ?>
                                    <span class="icon pre">待直播</span></div>
                                    <?php } elseif($vo['z_status'] == 2) { ?>
                                    <span class="icon liv">直播中</span></div>
                                    <?php } elseif($vo['z_status'] == 3) { ?>
                                    <span class="icon bck">已结束</span></div>
                                    <?php } ?>
                                <div class="live-user">{$vo.realname}</div>
                                <div class="clr"></div>
                            </div>
                            <ul class="item-panel text-info" data-id="{$vo.id}" data-stream="{$vo['group_id']}_{$vo['user_id']}">
                            </ul>
                            <div class="send">

                                <input type="text" name="message" class="pushmsg" />
                                <input type="hidden" name="group" class="sendgroup" value="{$vo['group_id']}_{$vo['user_id']}" />
                                <input type="hidden" name="group" class="sendname" value="{$vo.realname}" />
                                <botton type="button" class="btn-info btnn sendmsg">发送</botton>

                                <!--<input type="text"> <a class="btnn">发送</a>-->
                            </div>
                        </li>
                        </volist>
                        <li class="clr"></li>
                    </ul>
                </li>
                <li class="tab-content liveInfo" id="settings">
                    <form action="{:U('updateDetail')}" method="post" enctype="multipart/form-data" id="detailForm"
                          class="form-horizontal" role="form">
                        <ul>
                            <li class="setting-item">
                                <div class="label-title">标题</div>
                                <input type="text" name="title" class="title" value="{$streamList[0]['title']}">
                            </li>
                            <li class="setting-item">
                                <div class="label-title">简介</div>
                                <textarea name="live_intro" id="live_intro" class="info" style="width: 600px;height: 250px;">{:strip_tags($streamList[0]['intro'])}</textarea>
                            </li>
                            <li class="setting-item">
                                <div class="label-title">开始时间</div>
                                <div class="date-item">
                                    <div class='input-group date'>
                                        <input type='text' class="form-control form_datetime" id="start_time" name="start_time"
                                               value="<?php echo date('Y-m-d H:i', $streamList[0]['start_time']) ?>"/>

                                        <script type="text/javascript">
                                            $(".form_datetime").datetimepicker({
                                                format: 'yyyy-mm-dd hh:ii',
                                                autoclose: true,
                                                todayBtn: true,
                                                pickerPosition: "bottom-left",
                                                language:"zh-CN",
                                                minView: 2,
                                                forceParse: 0,
                                                minView: 0,
                                                minuteStep: 5
                                            });
                                        </script>
                                    </div>
                                </div>
                            </li>
                            <li class="setting-item">
                                <div class="label-title">缩略图</div>
                                <div id="uploader-demo">
                                    <!--用来存放item-->
                                    <div id="filePicker">选择图片</div>
                                </div>
                                <!--<div id="fileList" class="uploader-list"  <?php if($streamList[0]['image_url']) { ?>style="background:-->
                                <!--url('{$streamList[0]['image_url']}?imageView2/2/w/300/h/170') no-repeat;"<?php } ?>></div>-->
                                <div id="fileList" class="uploader-list">
                                    <div id="WU_FILE_0" class="file-item thumbnail">
                                        <img src="{$streamList[0]['image_url']|default='http://jianwei.appwuhan.net/Public/images/defaultpic.gif'}?imageView2/2/w/300/h/170"  style="height: 130px;max-width: inherit;" alt="">
                                        <!--<img src="{$streamList[0]['image_url']}?imageView2/2/w/300/h/170"  style="height: 130px;max-width: inherit;" alt="">-->
                                    </div>
                                </div>

        </li>
        </ul>
        <div class="setting-controls">
            <input type="hidden" name="image_url" id="image_url" value="{$streamList[0]['image_url']}">
            <input type="hidden" name="group_id" value="{$streamList[0]['group_id']}"/>
            <button type="submit" class="bttn btns-primary" id="save-btn">提交</button>
            <button type="button" class="bttn btns-default" id="reset-btn">重置</button>
        </div>
        </form>
        </li>
        <li class="tab-content" id="channel">
            <div class="detail-list">
                <table>
                    <thead>
                    <tr>
                        <th class="tb-number">序号</th>
                        <th class="tb-name">机位名称</th>
                        <th class="tb-user">直播人</th>
                        <th class="tb-ctrl">操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    <volist name="streamList" id="vo">
                        <tr class="item-drag livePos" value="0">
                            <td><input type="text" class="posSort form-control" style="text-align: center;"
                                       data-id="{$vo.id}" value="{$vo.pos_sort}"></td>
                            <td>
                                <div class="comment-text pos_name" title="双击修改信息"
                                     data-id="{$vo.id}"><?php if($vo['pos_name']){echo $vo['pos_name'];}else{echo $i.'号机位';} ?></div>
                            </td>
                            <td>{$vo.realname}</td>
                            <td>
                                <a href="javascript:;" class="download" data-id="{$vo.id}">获取视频</a>
                                |<a href="javascript:;" class="thumb" data-id="{$vo.id}">缩略图</a>
                                |<a href="javascript:;" class="rtmp" data-id="{$vo.id}">拉流</a>
                                |<a href="javascript:;" class="pushrtmp" data-id="{$vo.id}">推流</a>
                            </td>
                        </tr>
                    </volist>
                    </tbody>
                    <tr>
                        <td><button type="button" class="btn btn-sm btn-info" id="sortBtn">更新排序</button></td>
                    </tr>
                </table>
                <div class="clr"></div>
            </div>
            <div class="controls">
                <span>注：</span>机位通过拖动排序，机位名称双击进行修改。
            </div>
        </li>

        <li class="tab-content" id="comment">
            <iframe id="ifComment" src="{:U('Home/Comment/index')}?group_id={$Think.get.group_id}" width="100%"
                    height="800" frameborder="0"></iframe>
        </li>
        </ul>
    </div>
</div>
</div>
<div id="model" style="display: none">
    <input class="model modify-text">
    <button type="button" class="model sbtn sbtn-primary submit">OK</button>
    <button type="button" class="model sbtn sbtn-warning cancel">取消</button>
</div>

<style>
    #downBox .list, #bitBox .list {
        min-height: 200px;
    }

    #downBox .form-control, #bitBox .form-control {
        display: inline;
        width: auto;
    }
</style>
<!--视频m3u8列表-->
<div class="modal fade" id="downBox" tabindex="-1" role="dialog" aria-labelledby="m3u8list" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span
                        class="sr-only">Close</span></button>
                <h4 class="modal-title">

                    开始时间： <input size="16" type="text" value="{:date('Y-m-d')}" class="form-control form_datetime"
                                 id="sTime">
                    结束时间： <input size="16" type="text" value="{:date('Y-m-d')}" class="form-control form_datetime"
                                 id="eTime">
                    <button type="button" class="btn btn-sm btn-info" id="mediaBTN"><i
                            class="glyphicon glyphicon-search"></i> 搜索
                    </button>
                    <script type="text/javascript">
                        $(".form_datetime").datetimepicker({
                            format: 'yyyy-mm-dd',
                            autoclose: true,
                            todayBtn: true,
                            pickerPosition: "bottom-left",
                            language: "zh-CN",
                            minView: 2,
                            forceParse: 0
                        });


                    </script>
                </h4>
            </div>
            <div class="modal-body list">

                <div id="liveId" data-id=""></div>
                <ul id="sList" data-idlist="">
                    <div class="text-center">
                        <div class="loading"><span class="gauge-loader">Loading&#8230;</span>
                            <p>Loading...</p></div>
                    </div>
                    <hr>
                    <div class="col-sm-10"><input type="text" class="form-control" id="re_live" name="return_live"
                                                  value="{$streamList[0]['return_live']}"/></div>
                </ul>
            </div>
        </div>
    </div>
</div>

<!-- 查看浏览直播的详情 -->
<div class="modal fade" id="thumbModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <form action="http://upload.qiniu.com/imgThumb
        " method="post" id="liveForm" class="form-horizontal" role="form" enctype="multipart/form-data">
            <input name="token" type="hidden" value="{$liveToken}">
            <input name="x:liveId" type="hidden" id="thumbLiveId" value="0">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title">上传缩略图</h4>
                </div>
                <div class="modal-body list">
                    <div class="form-group">
                        <label for="thumb" class="col-sm-2 control-label"><span>缩略图：</span></label>
                        <div class="col-sm-10"><input type="file" class="form-control" id="thumb" name="file"/></div>
                        <div class="error"></div>
                    </div>
                    <div class="form-group" id="imgThumb">

                    </div>
                    <!--<input type="hidden" name="liveid" value="0" />-->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-danger" id="thumbBtn">保存</button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- 24小时拉流 -->
<div class="modal fade bs-example-modal-sm" tabindex="-1" id="h24rtmp" role="dialog" aria-labelledby="h24rtmp" aria-hidden="true">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
       <div id="rtmp" style="padding:15px"></div>
    </div>
  </div>
</div>

<!-- 24小时推流 -->
<div class="modal fade bs-example-modal-sm" tabindex="-1" id="h24PushRtmp" role="dialog" aria-labelledby="h24PushRtmp" aria-hidden="true">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
       <div id="PushRtmp1" style="padding:15px;">
        rtmp地址：<input type="text" class="form-control" value="" style="font-size: 12px;">
       </div>
       <div id="PushRtmp2" style="padding:15px;">
        直播码：<textarea  rows="4" class="form-control"  style="font-size: 12px;"></textarea>
       </div>

       <div  style="padding:15px">
        <p>
            <strong>注：</strong>每次点击获取推流码都会重新生成直播码，每个直播码有效期24小时！
        </p>
       </div>
    </div>
  </div>
</div>

<!-- 预览和打点 -->
<div class="modal fade" tabindex="-1" id="preview" role="dialog" aria-labelledby="preview" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title">视频预览与裁剪</h4>
            </div>
            <div class="modal-body">
                <div id="return_player"  class="prism-player"></div>
                <div class="btns text-center" style="padding-top:15px;display: block">
                    <button class="btn btn-sm btn-warning" type="button" id="setVSTime">设置开始时间</button>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <button class="btn btn-sm btn-warning" type="button" id="setVETime">设置结束时间</button>
                </div>
            </div>
            <div class="modal-footer" style="text-align: center">
                <form class="form-inline" role="form">
                    <div class="form-group">
                        生成新的视频：
                    </div>
                    <div class="form-group">
                        <label  for="v_start_time" style="display: inline">开始时间</label>
                        <input type="text" class="form-control" name="v_start_time" id="v_start_time">
                    </div>
                    <div class="form-group">
                        <label  for="v_end_time" style="display: inline">结束时间</label>
                        <input class="form-control" type="text" name="v_end_time" id="v_end_time">
                    </div>
                    <button type="button" class="btn btn-sm btn-info" id="makeNewM3U8">确定生成</button>
                </form>
            </div>
        </div>
    </div>
</div>

<div id="model-hidden" style="display:none">
    <div class="select-item">
        <span class="text"></span>
        <span class="delete"></span>
    </div>
</div>

<script src="__PUBLIC__/js/aleart.js"></script>
<script>

    var tmp;
    // 直播事件控制
    var liveEntity = new Vue({
        el: '#live',
        data: {
            isEdit: [],
            isCheck: [],
            items: [
//                {name:"1号机位",status:"0",user:"李威",image:"__PUBLIC__/img/test3.png"},
//                {name:"2号机位",status:"1",user:"李威",image:"__PUBLIC__/img/test3.png"},
//                {name:"3号机位",status:"2",user:"李威",image:"__PUBLIC__/img/test3.png"},
            ],
            selectNum: []
        },
        methods: {
            showPanel: function (index) {
                liveEntity.isEdit = [];
                liveEntity.isEdit[index] = true;
            },
            hidePanel: function (index) {
                liveEntity.isEdit = [];
                liveEntity.isEdit[index] = false;
            },
            checkitem: function (item, index) {
                if (this.isCheck.join("").length == 0) {
                    this.selectNum = item;
                }
                tmp = liveEntity.isCheck;
                liveEntity.isCheck = [];
                liveEntity.isCheck[index] = true;
            },
            add: function (item, index) {
                liveEntity.isCheck = [];
                liveEntity.isCheck = tmp;
                if (liveEntity.isCheck[index] == undefined) {
                    liveEntity.isCheck[index] = true;
                } else {
                    liveEntity.isCheck[index] = !liveEntity.isCheck[index];
                }
                console.log(item, index)
            },
            addList: function (item, index) {
                console.log(item, index)
            },
            offCheck: function () {
                liveEntity.isCheck = [];
            }
        }
    });

    var uploader;
    $(function () {

        $('#reset-btn').click(function () {
            $("#fileList .thumbnail").html('<img src="{$streamList[0]['image_url']}?imageView2/2/w/300/h/170"  style="height: 130px;" alt="">');
            uploader.reset();
            $('#detailForm')[0].reset();
            $('#save-btn').attr('type', 'submit');
        });

        // tabs
        $(".nav-tabs li").click(function () {

            $(this).addClass("active").siblings().removeClass("active");
            var href = $(this).data("href");
            $(".tab-content").removeClass("active");
            $('#' + href).addClass("active");
            if (href == "live") {
                $("#addr-model").hide();
            } else {
                $("#addr-model").removeClass("show");
            }

            if(href == 'settings') {


                uploader = WebUploader.create({
                    auto: false,
                    swf: 'http://cdn.bootcss.com/webuploader/0.1.1/Uploader.swf',
                    server: 'http://upload.qiniu.com',
                    pick: '#filePicker',
                    accept: {
                        title: 'Images',
                        extensions: 'gif,jpg,jpeg,bmp,png',
                        mimeTypes: 'image/*'
                    },
                    thumb:{
                        crop: false,
                    },
                    compress:false,
                    formData:{
                        token:"{$uploadToken}",
                    },
                    fileNumLimit:1
                });

                uploader.on('beforeFileQueued',function(){
                    $("#save-btn").attr('type','button');
                    $("#fileList").empty();
                    uploader.reset();
                })

                uploader.on( 'fileQueued', function( file ) {
                    var $li = $(
                                    '<div id="' + file.id + '" class="file-item thumbnail">' +
                                    '<img>' +
                                    '</div>'
                            ),
                            $img = $li.find('img');
                    $("#fileList").append( $li );
                    uploader.makeThumb( file, function( error, src ) {
                        if ( error ) {
                            $img.replaceWith('<span>不能预览</span>');
                            return;
                        }
                        $img.attr( 'src', src );
                    }, 1, 130 );
                });

                uploader.on( 'uploadProgress', function( file, percentage ) {
                    var $li = $( '#'+file.id ),
                            $percent = $li.find('.progress span');
                    if ( !$percent.length ) {
                        $percent = $('<p class="progress"><span></span></p>')
                                .appendTo( $li )
                                .find('span');
                    }

                    $percent.css( 'width', percentage * 100 + '%' );
                });


                uploader.on( 'uploadSuccess', function( file ,response ) {
                    $( '#'+file.id ).addClass('upload-state-done');
                    $("#image_url").val('{:C("IMAGE_HOST")}'+response.key);
                    $("#save-btn").attr('type','submit');
                    $("#detailForm").submit();
                });

                uploader.on( 'uploadError', function( file ) {
                    var $li = $( '#'+file.id ),
                            $error = $li.find('div.error');

                    if ( !$error.length ) {
                        $error = $('<div class="error"></div>').appendTo( $li );
                    }

                    $error.text('上传失败');
                });

                uploader.on( 'uploadComplete', function( file ) {
                    $( '#'+file.id ).find('.progress').remove();
                });


            } else {
                if(uploader) {
                    $("#fileList .thumbnail").html('<img src="{$streamList[0]['image_url']}?imageView2/2/w/300/h/170"  style="height: 130px;" alt="">');
                    uploader.reset();
                    uploader.destroy();
                }
            }


            if (href == "comment") {
                $("#comment .comment-text").ellipsis({
                    row: 2
                });
            }
        });

        //复制特效
        $("#addr-model .label").click(function () {
            var item = $(this);
            $(this).parent().addClass("copying");
            setTimeout(function () {
                item.parent().removeClass("copying");
            }, 500);
        });

        // 复制，剪切板
        var clipboard = new Clipboard('#addr-model .label');
        // clipboard.on('success', function(e) {
        //     console.log(e);
        // });
        // clipboard.on('error', function(e) {
        //     console.log(e);
        // });

        // 直播弹框
        $(document).on("click", ".tab-content .link", function () {
            $("#addr-model").show().toggleClass("show");
        });

        // 直播事件控制
        var liveEntity = new Vue({
            el: '#live',
            data: {
                isEdit: false,
            },
            methods: {
                showPanel: function () {
                    this.isEdit = true;
                },
                hidePanel: function () {
                    this.isEdit = false;

                }
            }
        })

        // 时间设置



        $("#save-btn").click(function () {
            if (!$(this).is(":submit")) {
                uploader.upload();
            }
        })

    })


    $(".download").click(function () {
        $('#downBox').modal('show')
        $("#sList").load("{:U('Oss/ajaxMediaList')}?id=" + $(this).data('id'), function (d) {
            $(d).find('img').each(function () {
                var idList = $("#downBox .list ul").data('idlist');
                idList = idList.split(',');
                if ($.inArray($(this).data('streamid') + "", idList) == -1) {
                    getProgress($(this).parent(), $(this).data('streamid'));
                }
            })
        })
        $('#liveId').data('id', $(this).data('id'));
    })

    $('#downBox').on('hidden.bs.modal', function () {
        $("#sList").html('<div class="text-center"><div class="loading"><span class="gauge-loader">Loading&#8230;</span><p>Loading...</p></div></div>');
        //$('#liveId').data('id','');
    })

    $("#downBox").on('click','.returnLive',function () {
        var _this = this;
        var id = $(_this).data('id');
        var url = $(_this).data('url');
        $.post('{:U("Oss/ajaxSetReturnLive")}', {id:id,url:url}, function (data) {
            if(data != 0) {
                $("#sList").load("{:U('Oss/ajaxMediaList')}?id="+$(_this).data('id'),function(d){
                    $(d).find('img').each(function(){
                        var idList=$("#downBox .list ul").data('idlist');
                        idList=idList.split(',');
                        if($.inArray($(this).data('streamid')+"", idList)==-1){
                            getProgress($(this).parent(),$(this).data('streamid'));
                        }
                    })
                })
                $('#liveId').data('id',$(_this).data('id'));

            } else {
                $.alert('设置失败，请重试');
            }
        });
    });


    $('.thumb').click(function () {
        $('#thumbModal').modal('show');
        $('#thumbModal input[name="liveid"],#thumbLiveId').val($(this).data('id'));
        $.get('{:U("getLiveThumb")}?liveid=' + $(this).data('id'), function (data) {
            if (data) {
                $('#imgThumb').html('<img src="' + data + '" height="130" />');
            } else {
                $('#imgThumb').html('');
            }
        })

    });

    $('#thumbBtn').click(function () {
        if ($('#thumb').val() == '') {
            $('#thumbModal .error').html('还未选择文件');
            return false;
        } else {
            $('#thumbModal .error').html('');
        }
    });

    $(".rtmp").click(function () {
        $.get("{:U('ajaxGetLongRtmp')}?id=" + $(this).data('id'), function (data) {
            if (data != -1) {
                $("#rtmp").html(data);
                $("#h24rtmp").modal('show');
            }
        })
    })

    $(".pushrtmp").click(function(){
        $.get("{:U('ajaxGetLongPushRtmp')}?id="+$(this).data('id'),function(data){
            if(data!=-1){

                var arr=data.split('/');
                var s1=arr[0]+"//"+arr[2]+"/"+arr[3];
                var s2=arr[4];


                $("#PushRtmp1 input").val(s1);
                $("#PushRtmp2 textarea").html(s2);
                $("#h24PushRtmp").modal('show');
            }
        })
    })

</script>
<script>
    function editReturn(id, obj) {
        if (confirm("是否确定修改此机位的回看？")) {
            $(obj).attr("disabled", "disabled").html('修改中...');
            $.ajax({
                type: 'post',
                url: '{:U('ajaxEditReturnLive')}',
                data: {id: id, returnLive: $(obj).prev('input').val()},
                async: false,
                success: function (data) {
                    if (data < 0) {
                        alert('修改失败!');
                    } else {
                        $(obj).removeAttr('disabled').html('确定修改');
                        if (data > 0) {
                            alert('修改成功！');
                        }
                    }
                }
            });
        }

    }

$(document).ready(function () {
    function formatTime(num) {
        var d = new Date(num * 1000);
        var h = d.getHours() - 8;
        h = h > 9 ? h : "0" + h;
        var m = d.getMinutes();
        m = m > 9 ? m : "0" + m;
        var s = d.getSeconds();
        s = s > 9 ? s : "0" + s;
        var str = "";
        str += h + ":";
        str += m + ":";
        str += s;
        return str;
    }
    var ws = new ReconnectingWebSocket("ws://socket.appwuhan.net:10088");
    var return_player;

    $("#sList").on("click", ".previewStream", function () {

        $("#makeNewM3U8").data('stream', $(this).data('stream'));
        $("#makeNewM3U8").data('time', $(this).parents('li').find('.vtime').text());
        $("#makeNewM3U8").data('duration', $(this).parents('li').find('.vtime').data('duration'));

        return_player = new prismplayer({
            id: "return_player",
            source: 'http://whtv-out.oss-cn-hangzhou.aliyuncs.com/' + $(this).data('oss'),
            autoplay: false,
            isLive: false,
            width: "100%",
            height: "500px",
            showBarTime: 3600 * 24 * 1000
        });
        return_player.on("play", function () {
            $("#makeNewM3U8").data('videolong', return_player.getDuration());
        });

        $("#preview").modal('show');
    });

    $('#preview').on('hidden.bs.modal', function (e) {
        $("#return_player").empty();
        $("#v_start_time,#v_end_time").val("");
        $("#makeNewM3U8").html('确定生成').prop('disabled', false);
    });

    $("#setVSTime").click(function () {

        if (formatTime(return_player.getCurrentTime()) < $("#v_end_time").val() || $("#v_end_time").val() == "") {
            $("#v_start_time").val(formatTime(return_player.getCurrentTime())).data("t", return_player.getCurrentTime());
        } else {
            alert("不能大于结束时间");
        }
    });

    $("#setVETime").click(function () {
        return_player.pause();

        if (formatTime(return_player.getCurrentTime()) > $("#v_start_time").val() || $("#v_start_time").val() == "") {
            $("#v_end_time").val(formatTime(return_player.getCurrentTime())).data("t", return_player.getCurrentTime());
        } else {
            alert("不能小于开始时间");
        }

    });

    $("#makeNewM3U8").on("click", function () {
        if (confirm("是否确定生成新的视频文件？")) {
            var _this = this;
            if ($("#v_end_time").val() != "" && $("#v_start_time").val() != "" && $("#v_end_time").val() > $("#v_start_time").val() && confirm('是否确定生成新的视频文件?')) {
                $(_this).html('生成中...').prop('disabled', true);
                var vTime = $(_this).data('time');
                vTime = vTime.split("—");

                var sTime = vTime[0];
                var tmp = sTime.split(" ");
                var st = new Date(sTime);
                sTime = Math.round(st.getTime() / 1000 + parseInt($("#v_start_time").data("t")));

                var eTime = tmp[0] + " " + vTime[1];
                var et = new Date(eTime);

                var videolong = Math.round(Math.abs(parseInt(et.getTime()) - parseInt(st.getTime())) / 1000);

                var videolong2 = Math.round($(_this).data('duration'));

                eTime = Math.round(et.getTime() / 1000 - (videolong - parseInt($("#v_end_time").data("t")))) + (videolong - videolong2);


                $.ajax({
                    url: '{:U("Oss/ajaxMakeM3U8")}',
                    data: {sTime: sTime, eTime: eTime, stream: $(_this).data('stream')},
                    //async:false,
                    success: function (data) {
                        if (data.code == 0) {
                            alert("成功生成新的视频文件！");
                            $("#preview").modal('hide');
                            $("#sList").load("{:U('Oss/ajaxMediaList')}?id=" + $('#liveId').data('id') + "&sTime=" + $("#sTime").val() + "&eTime=" + $("#eTime").val());
                        } else {
                            alert(data.msg);
                            $(_this).html('确定生成').prop('disabled', false);
                        }
                    }
                })
            }
        }
    })


    $(window).load(function () {
        var scrollTop = localStorage.getItem("scrollTop") == null ? 0 : localStorage.getItem("scrollTop");
        $(".sidebar-list").parent().scrollTop(scrollTop);
        $(".sidebar-list").click(function () {
            localStorage.setItem("scrollTop", $(this).parent().scrollTop());
        });
    });

    $("#setAuthBtn").click(function () {
        $('#myModal').modal('show')
    });


    $('#authBox').on('hidden.bs.modal', function () {
        $("#sList").html('<div class="text-center"><div class="loading"><span class="gauge-loader">Loading&#8230;</span><p>Loading...</p></div></div>');
    })


    $(".download").click(function () {
        $('#downBox').modal('show')
        $("#sList").load("{:U('Oss/ajaxMediaList')}?id=" + $(this).data('id'), function (d) {
            $(d).find('img').each(function () {
                var idList = $("#downBox .list ul").data('idlist');
                idList = idList.split(',');
                if ($.inArray($(this).data('streamid') + "", idList) == -1) {
                    getProgress($(this).parent(), $(this).data('streamid'));
                }
            })
        })
        $('#liveId').data('id', $(this).data('id'));
    })

    $('#downBox').on('hidden.bs.modal', function () {
        $("#sList").html('<div class="text-center"><div class="loading"><span class="gauge-loader">Loading&#8230;</span><p>Loading...</p></div></div>');
        //$('#liveId').data('id','');
    })

    $("#mediaBTN").click(function () {
        $("#sList").load("{:U('Oss/ajaxMediaList')}?id=" + $('#liveId').data('id') + "&sTime=" + $("#sTime").val() + "&eTime=" + $("#eTime").val(), function (d) {
            $(d).find('img').each(function () {
                var idList = $("#sList").data('idlist');
                idList = idList.split(',');
                if ($.inArray($(this).data('streamid') + "", idList) == -1) {
                    getProgress($(this).parent(), $(this).data('streamid'));
                }
            })
        })
    })

    $("#sList").on("click", ".getURL", function () {
        var obj = this;
        $.ajax({
            dataType: "json",
            url: "{:U('Oss/transMTS')}?file=" + $(obj).data('stream') + "&liveid=" + $('#liveId').data("id"),
            success: function (d) {
                switch (d.status) {
                    case 0:
                        $.alert(d.msg + "，请稍后重试！");
                        break;
                    default:
                        var parent = $(obj).parent();
                        var idList = $("#sList").data('idlist');
                        idList = idList.split(',');
                        if ($.inArray(d.msg.stream_id, idList) == -1) {
                            idList[idList.length] = d.msg.stream_id;
                        }
                        idList = idList.join(',');
                        idList = idList.replace(/^,/, "");
                        $("#sList").data('idlist', idList);
                        $(obj).parent().html('<img src="__PUBLIC__/live/img/mtsloading.gif"   /> 转码中...');
                        getProgress(parent, d.msg.stream_id);
                }
            }
        })
    })



    var val;
    $(".pos_name").dblclick(function (e) {
        e.preventDefault();
        e.stopPropagation();
        val = $(this).text();
        $(this).html("<input type='text' class='i_pos form-control' id='" + $(this).data("id") + "' />");
        $(this).find("input").focus().val(val);
    })


    $(".pos_name").on("blur", ".i_pos", function () {
        var obj = this;
        if ($(obj).val() !== val) {
            if (confirm("是否确定修改此机位信息？")) {
                $.get("{:U('ajaxEditPosName')}?id=" + $(obj).attr("id") + "&posName=" + $(obj).val(), function (data) {
                    if (data == 1) {
                        $(obj).parent().html($(obj).val());
                    } else {
                        $(obj).parent().html(val);
                    }
                })
            } else {
                $(obj).parent().html(val);
            }
        } else {
            $(obj).parent().html(val);
        }
    })


    $('#pushStream').on('click', function (e) {
        e.preventDefault();
        var item = $(this);
        if (item.get(0).checked) {
            $.confirm("确定开启所有的直播通道吗？", function () {
                $.get("{:U('ajaxGroupStreamOn')}?groupid=" + item.data('groupid'), function (data) {
                    if (data.status == 0) {
                        $(".text-info").each(function () {
                            $(this).load("{:U('showBTNs')}?id=" + $(this).data('id'))
                        })
                        item.prop("checked", true);
                    } else {
                        $.alert(data.msg);
                    }
                })
            }, function () {
            })
        } else {
            $.confirm("确定关闭所有的直播通道吗？", function () {
                $.get("{:U('ajaxGroupStreamOff')}?groupid=" + item.data('groupid'), function (data) {
                    if (data.status == 0) {
                        $(".text-info").each(function () {
                            $(this).load("{:U('showBTNs')}?id=" + $(this).data('id'))
                        })
                        item.prop("checked", false);

                    } else {
                        $.alert(data.msg);
                    }
                })
                // var data={action:'closeAllStream',group:'{$Think.get.group_id}'};
                // data=JSON.stringify(data)
                // ws.send(data);
            }, function () {
            })
        }


    });

    $("#liveStatus").click(function (e) {
        e.preventDefault();
        if ($(this).is(":checked") == false) {
            isLsEnd = 1;
            var item = $(this);
            $.confirm("确定结束所有直播吗？", function () {
                $.get("{:U('ajaxLiveStatusOff')}?groupid=" + item.data('groupid'), function (data) {
                    if (data.status == 0) {
                        location.reload();
                    } else {
                        $.alert(data.msg);
                    }
                })
                // var data={action:'closeAllStream',group:'{$Think.get.group_id}'};
                // data=JSON.stringify(data)
                // ws.send(data);
            }, function () {
                // 取消func
            });
        } else {
            var item = $(this);
            $.confirm("确定将所有直播都开启吗？", function () {
                $.get("{:U('ajaxLiveStatusOn')}?groupid=" + item.data('groupid'), function (data) {
                    if (data.status == 0) {
                        location.reload();

                    } else {
                        $.alert(data.msg);
                    }
                })
                // var data={action:'closeAllStream',group:'{$Think.get.group_id}'};
                // data=JSON.stringify(data)
                // ws.send(data);
            }, function () {
                // 取消func
            });
        }
    });


    $('#sortBtn').on('click', function () {
        var data = [];
        $('.livePos .posSort').each(function (i) {
            data[i] = [$(this).data('id'), $(this).val()];
        });

        $.post('{:U("ajaxUpdateSort")}?group_id={$streamList[0]["group_id"]}', {'data': data}, function (data) {
            if (data == 1) {
                $.alertRecall('排序更新成功', function () {
                    window.location.reload();
                });
            } else {
                $.alertRecall('服务器繁忙，请稍后重试！');
            }
        });
    });


    $("#addr-model .label").click(function () {
        var item = $(this);
        $(this).parent().addClass("copying");
        setTimeout(function () {
            item.parent().removeClass("copying");
        }, 500);
    });

    var clipboard = new Clipboard('#addr-model .label');

    $(".imgClass").click(function (e) {
        e.stopPropagation();
        $("#addr-model").show().addClass("show");
    });

    $(".close-cp a").click(function () {
        $("#addr-model").removeClass("show").hide();
    })

    function getProgress(obj, stream_id) {
        var t;
        $.ajax({
            type: "json",
            url: "{:U('Oss/ajaxGetProgress')}?stream_id=" + stream_id,
            success: function (data) {
                if (data.status == 1) {
                    var percent = data.msg;
                    obj.html('<img src="__PUBLIC__/live/img/mtsloading.gif" />  转码中...')
                    if (percent == 100) {
                        clearTimeout(t);
                        obj.html('<a class="btn btn-xs btn-danger downloadMts" target="_blank"  href="http://download.appwuhan.net/Live/download.html?id=' + stream_id + '">下载</a>')
                    }
                }
            }
        });
        t = setTimeout(function () {
            getProgress(obj, stream_id);
        }, 3000);
    }


    $('.thumb').click(function () {
        $('#thumbModal').modal('show');
        $('#thumbModal input[name="liveid"],#thumbLiveId').val($(this).data('id'));
        $.get('{:U("getLiveThumb")}?liveid=' + $(this).data('id'), function (data) {
            if (data) {
                $('#imgThumb').html('<img src="' + data + '" height="130" />');
            } else {
                $('#imgThumb').html('');
            }
        })

    });

    $('#thumbBtn').click(function () {
        if ($('#thumb').val() == '') {
            $('#thumbModal .error').html('还未选择文件');
            return false;
        } else {
            $('#thumbModal .error').html('');
        }
    });


    $('.bitRate').on('click', function () {
        $('#bitBox').modal('show');

        $("#bList #txt").html('<div class="alert alert-info" role="alert">请选择时间范围查询视频</div>');

        $('#liveId2').data('id', $(this).data('id'));
    })


    /*评论面板开关*/
    $('#comment').on('click', function () {
        if ($(this).hasClass('btn-info')) {
            $(this).removeClass('btn-info').addClass('btn-default');
            $(".liveView").slideDown().siblings('.tab').slideUp();

        } else {
            $(this).removeClass('btn-default').addClass('btn-info').siblings().removeClass('btn-info').addClass('btn-default');
            ;
            $(".comment").slideDown().siblings('.tab').slideUp();
        }
    });

    $('.sendmsg').on('click', function () {
        if (!$(this).hasClass('sending')) {
            var name = $(this).parent().find('.sendname').val();
            var group = $(this).parent().find('.sendgroup').val();
            var content = $.trim($(this).parent().find('.pushmsg').val());

            if (!content) {
                alert('消息不能为空');
                return false;
            }
            $(this).addClass('sending');


            var data = {action: 'backend_write_data', group: group, name: name, content: content};
            data = JSON.stringify(data)
            ws.send(data);
            // alert('发送成功');
        }
    });

    ws.onmessage = function (evt) {
        var received_msg = $.parseJSON(evt.data);

        if (received_msg.type == 'ping') {
            var data = {type: 'pong'};
            data = JSON.stringify(data)
            ws.send(data);
            return;
        }

        if (received_msg.act == 'backend') {
            if (received_msg.status == 1) {
                $('.sendmsg').removeClass('sending');
                $('.pushmsg').val("");
                alert('发送成功');
            } else {
                alert('发送失败');
            }
        }
    }

    $(".rtmp").click(function () {
        $.get("{:U('ajaxGetLongRtmp')}?id=" + $(this).data('id'), function (data) {
            if (data != -1) {
                $("#rtmp").html(data);
                $("#h24rtmp").modal('show');
            }
        })
    })

    $("#searchInput").on('keyup', function () {
        $(".sidebar-list").parent().html($(".sidebar-list").parent().html().replace(/<\/?span.*?>/g, ''));

        if ($.trim($(this).val()) != '') {
            var reg = new RegExp('(' + $.trim($(this).val()) + ')', 'g');
            $(".sidebar-list a").each(function (index, item) {
                //$(item).find('span')

                var tmp = item.innerHTML;

                if (reg.test(tmp)) {
                    var i = tmp.replace(reg, '<span class="selected">' + RegExp.$1 + '</span>');
                    item.innerHTML = i;
                    $(this).parent().show();
                } else {
                    $(this).parent().hide();
                }
            });
        } else {

            $(".sidebar-list").show();
        }
    });
    /*机位管理界面切换*/
    $("#managePos").click(function () {
        if ($(this).hasClass('btn-info')) {
            $(this).removeClass('btn-info').addClass('btn-default');
            $(".liveView").slideDown().siblings('.tab').slideUp();

        } else {
            $(this).removeClass('btn-default').addClass('btn-info').siblings().removeClass('btn-info').addClass('btn-default');
            $(".livePos").slideDown().siblings('.tab').slideUp();
        }
    })


    $('.text-info').on('click', '.item-btn', function (e) {


        e.preventDefault();
        var item = $(this);
        console.log(item.data('status'));
        switch (item.data('status')) {
            case 3:
                $.confirm("确定结束<span style='color:red;font-weight: bold;'>" + item.parents("li").find(".zbRen").text() + "</span>的直播吗？<p style='color:red;font-size:12px'>（结束后不能重新开启）</p>", function () {
                    $.get("{:U('ajaxLiveOff')}?liveId=" + item.data('id') + "&stream=" + item.data('stream'), function (data) {
                        if (data.status == 0) {
                            window.location.reload();
//                            item.parents('.text-info').load("{:U('showBTNs')}?id=" + item.data('id'));
//                            if (data.groupId == 3) {
//                                $('#liveStatus').prop('checked', false);
//                                $('#liveStatus').prop("disabled", true);
//                                $('#liveStatus').next().addClass("disabled");
//
//                                $('#pushStream').parents(".col-50").remove();
//                            }
                        } else {
                            $.alert(data.msg);
                        }
                    })

                    // var data={action:'closeStream',group:'{$Think.get.group_id}',id:item.data('id')};
                    // data=JSON.stringify(data)
                    // ws.send(data);

                }, function () {
                })
                break;
            case 1:
                $.confirm("确定开启<span style='color:red;font-weight: bold;'>" + item.parents("li").find(".zbRen").text() + "</span>的直播通道吗？", function () {
                    $.get("{:U('ajaxStreamOn')}?liveId=" + item.data('id') + "&stream=" + item.data('stream'), function (data) {

                        if (data.status == 0) {
                            window.location.reload();
//                            item.parents('.text-info').load("{:U('showBTNs')}?id=" + item.data('id'));
//                            if (data.groupId == 1) {
//                                $('#pushStream').prop('checked', true);
//                            }
                        } else {
                            $.alert(data.msg);
                        }
                    })
                }, function () {
                })
                break;
            case 0:
                $.confirm("确定关闭<span style='color:red;font-weight: bold;'>" + item.parents("li").find(".zbRen").text() + "</span>的直播通道吗？", function () {
                    $.get("{:U('ajaxStreamOff')}?liveId=" + item.data('id') + "&stream=" + item.data('stream'), function (data) {
                        if (data.status == 0) {
                            window.location.reload();
//                            item.parents('.text-info').load("{:U('showBTNs')}?id=" + item.data('id'));
//                            if (data.groupId == 0) {
//                                $('#pushStream').prop('checked', false);
//                            }
                        } else {
                            $.alert(data.msg);
                        }
                    });

                    var data = {action: 'closeStream', group: '{$Think.get.group_id}', id: item.data('id')};
                    data = JSON.stringify(data)
                    ws.send(data);


                }, function () {
                })
                break;
            case 4:
                $.confirm("确定<span style='color:red;font-weight: bold;'>" + item.parents("li").find(".zbRen").text() + "</span>的直播进行测试吗？<p style='color:red;font-size:12px'>（结束后不能重新开启）</p>", function () {
                    $.get("{:U('ajaxSetLiveTesting')}?liveId=" + item.data('id') + "&stream=" + item.data('stream'), function (data) {
                        if (data.status == 0) {
                            window.location.reload();
//                            item.parents('.text-info').load("{:U('showBTNs')}?id=" + item.data('id'));
//                            if (data.groupId == 3) {
//                                $('#liveStatus').prop('checked', false);
//                                $('#liveStatus').prop("disabled", true);
//                                $('#liveStatus').next().addClass("disabled");
//
//                                $('#pushStream').parents(".col-50").remove();
//                            }
                        } else {
                            $.alert(data.msg);
                        }
                    })

                    // var data={action:'closeStream',group:'{$Think.get.group_id}',id:item.data('id')};
                    // data=JSON.stringify(data)
                    // ws.send(data);

                }, function () {
                })
                break;
        }
    })

    $(".statusbtnlist .panel-btn:not(.testing)").click(function(){
        var _this=this;
        //console.log($(_this).parents('.btnlist').data('groupid'))
        $.ajax({
            url:"{:U('ajaxSetLiveStatus')}",
            async:false,
            data:{group_id:$(_this).parents('.statusbtnlist').data('groupid'),status:$(_this).data('status')},
            success:function(data){
                if(data.status===0){
                    location.reload();

                }else{
                    $.alert(data.msg);
                }
            }
        })
    });

    /*评论面板开关*/
    $('#verify').click(function () {
        var _this = this;
        var status = $(this).data('status');
        $.post('{:U("setLiveVerify")}?group_id={$_GET["group_id"]}', {'status': status}, function (data) {
            if (data['status'] != 2) {
                if (data.status == 1) {
                    $(_this).html('先发后审');
                    $(_this).data('status', 0);
                } else {
                    $(_this).html('先审后发');
                    $(_this).data('status', 1);
                }
                $.alert(data.msg);
            } else {
                $.alert(data.msg);
            }
        })
    });


        $(".text-info").each(function () {
            $(this).load("{:U('showBTNs')}?id=" + $(this).data('id'))
        })

    })

</script>
</body>
</html>